package dailycheckin

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"menu-generation-go/database"
	"menu-generation-go/handlers/common"
	"menu-generation-go/models"
	"time"
)

type CheckinHandler struct {
	DB *database.Database
}

func NewCheckinHandler(db *database.Database) *CheckinHandler {
	return &CheckinHandler{DB: db}
}

// 打卡状态响应
type CheckinStatusResponse struct {
	Checked bool `json:"checked"`
}

// 打卡历史记录
type CheckinRecord struct {
	Date string `json:"date"`
	Time string `json:"time"`
}

// 打卡历史响应
type CheckinHistoryResponse struct {
	Days    int             `json:"days"`
	Records []CheckinRecord `json:"records"`
}

// 获取打卡状态
func (h *CheckinHandler) GetCheckinStatus(c *gin.Context) {
	type CheckinRequest struct {
		UserId int `json:"userId"`
	}

	var input CheckinRequest
	if err := c.ShouldBindJSON(&input); err != nil {
		common.SendErrJSON("无效userId:"+err.Error(), c)
		return
	}
	today := time.Now().Format("2006-01-02")
	var user models.MenuUser
	if h.DB.DB.Where("id = ?", input.UserId).First(&user).Error != nil {
		common.SendErrJSON("无效userId", c)
		return
	}

	var count int64
	h.DB.GetDB().Model(&models.MenuUserCheckin{}).
		Where("user_id = ? AND checkin_date = ?", input.UserId, today).
		Count(&count)

	common.Ok(c, CheckinStatusResponse{
		Checked: count > 0,
	})
}

// 执行打卡
func (h *CheckinHandler) Checkin(c *gin.Context) {
	type CheckinRequest struct {
		UserId int `json:"userId"`
	}

	var input CheckinRequest
	if err := c.ShouldBindJSON(&input); err != nil {
		common.SendErrJSON("无效userId:"+err.Error(), c)
		return
	}
	now := time.Now()
	today := now.Format("2006-01-02")

	var user models.MenuUser
	if h.DB.DB.Where("id = ?", input.UserId).First(&user).Error != nil {
		common.SendErrJSON("无效userId", c)
		return
	}

	// 检查是否已打卡
	var existingCheckin models.MenuUserCheckin
	result := h.DB.DB.Where("user_id = ? AND checkin_date = ?", input.UserId, today).First(&existingCheckin)

	if result.Error == nil {
		common.SendErrJSON("今日已打卡", c)
		return
	}

	// 创建打卡记录
	checkin := models.MenuUserCheckin{
		UserID:      input.UserId,
		OrgId:       user.OrgID,
		CheckinDate: today,
		CheckinTime: now,
	}

	if err := h.DB.DB.Create(&checkin).Error; err != nil {
		common.SendErrJSON("打卡失败", c)
		return
	}

	// 更新用户coins
	h.DB.DB.Model(&models.MenuUser{}).
		Where("id = ?", input.UserId).
		UpdateColumn("coins", gorm.Expr("coins + ?", 1))

	common.Ok(c, "打卡成功")
}

// 获取打卡历史
func (h *CheckinHandler) GetCheckinHistory(c *gin.Context) {
	type CheckinRequest struct {
		UserId int `json:"userId"`
	}

	var input CheckinRequest
	if err := c.ShouldBindJSON(&input); err != nil {
		common.SendErrJSON("无效userId:"+err.Error(), c)
		return
	}
	now := time.Now()
	year, month, _ := now.Date()

	// 本月第一天
	firstOfMonth := time.Date(year, month, 1, 0, 0, 0, 0, now.Location())

	var records []models.MenuUserCheckin
	h.DB.GetDB().Where("user_id = ? AND checkin_time >= ?", input.UserId, firstOfMonth).
		Order("checkin_time DESC").
		Find(&records)

	// 格式化记录
	var formattedRecords []CheckinRecord
	for _, r := range records {
		formattedRecords = append(formattedRecords, CheckinRecord{
			Date: r.CheckinDate,
			Time: r.CheckinTime.Format("15:04:05"),
		})
	}

	// 本月打卡天数
	var days int64
	h.DB.GetDB().Model(&models.MenuUserCheckin{}).
		Where("user_id = ? AND checkin_time >= ?", input.UserId, firstOfMonth).
		Count(&days)

	common.Ok(c, CheckinHistoryResponse{
		Days:    int(days),
		Records: formattedRecords,
	})
}
